package com.yy.controller;

import com.yy.pojo.Category;
import com.yy.pojo.Result;
import com.yy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
//新增分类
    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    //查询分类列表
    @GetMapping
    public Result<List<Category>> list(){
        List<Category> listCategory= categoryService.list();
        return Result.success(listCategory);
    }

    //获取分类详情
    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    //更新文章分类
    @PutMapping
    public Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category){
        categoryService.updateCategory(category);
        return Result.success();
    }

    //删除文章
    @DeleteMapping
    public Result deleteCategory(@RequestParam Integer id){
        try {
            if(categoryService.findById(id)==null){
                return Result.error("没有此文章");
            }
            categoryService.delete(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("此分类下有文章，请先删除文章");
        }
    }
}
